package user

import (
	"api/pkg/auth"
	"api/pb/user"
	"context"
	"strconv"
	"time"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.User) (resp *types.TokenResponse, err error) {
	u, err := l.svcCtx.UserRpc.GetUserByPassword(l.ctx, &user.UserInfo{Name: req.Name, Password: req.Password})
	if err != nil {
		return nil, err
	}

	expire := l.svcCtx.Config.Auth.AccessExpire
	token, err := auth.GenerateJWTToken(strconv.Itoa(int(u.Id)), l.svcCtx.Config.Auth.AccessSecret, expire)
	if err != nil {
		return nil, err
	}

	return &types.TokenResponse{
		User:         types.User{Id: u.Id, Name: u.Name},
		AccessToken:  token,
		AccessExpire: time.Now().Add(expire * time.Second).Unix(),
		RefreshAfter: time.Now().Add(expire * time.Second / 2).Unix(),
	}, nil
}
